import creatsign from './creatsign.js'
const httpRequestJpaasUrl = 'https://zwfw.gansu.gov.cn/jpaas-jags-server/interface/'

let time = new Date().getTime(); // 获取当前时间戳
const jpaasRequest = {
    utf8StrToBytes: (utf8Str) => {
        let ens = encodeURIComponent(utf8Str)
        let es = unescape(ens)
        let esLen = es.length
        let words = []
        for (let i = 0; i < esLen; i++) {
            words[i] = es.charCodeAt(i)
        }
        return words
    },
    encode: (b, pos, len) => {
        let hexCh = new Array(len * 2)
        let hexCode = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F')
        for (let i = pos, j = 0; i < len + pos; i++, j++) {
            hexCh[j] = hexCode[(b[i] & 0xff) >> 4]
            hexCh[++j] = hexCode[b[i] & 0x0f]
        }
        return hexCh.join('')
    },
    /**
     * 创建签名
     * @param {object} params 
     * @returns {string}
     */
    createSign: (params) => {
        let inputtext = 'app_id=' + params.app_id + '&biz_content=' + JSON.parse(JSON.stringify(params.biz_content)) + '&charset=' + params.charset + '&interface_id=' + params.interface_id + '&origin=' + params.origin + '&timestamp=' + params.timestamp + '&version=' + params.version;
        let dataBy = jpaasRequest.utf8StrToBytes(inputtext)
        let sm3 = new creatsign()
        sm3.update(dataBy, 0, dataBy.length)
        let sm3Hash = sm3.doFinal()
        let sm3HashHex = jpaasRequest.encode(sm3Hash, 0, sm3Hash.length)
        return sm3HashHex.toLowerCase()
    },
    /**
     * 基础请求方法
     * @param {object} params 
     * @returns {Promise}
     */
    gateway: (params = {}) => {
        return new Promise((resolve, reject) => {
            wx.request({
                url: httpRequestJpaasUrl + "gateway.do",
                method: 'POST',
                data: params,
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                },
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.data)
                    } else {
                        reject(new Error(`HTTP ${res.statusCode}: ${res.errMsg}`))
                    }
                },
                fail: (err) => {
                    reject(new Error(`请求失败: ${err.errMsg}`))
                }
            })
        })
    },

    getData: async ({
        app_id,
        interface_id,
        params = {},
    }, header) => {
        try {
            let baseparams = {
                version: "1.0",
                charset: "UTF-8",
                origin: "2",
                timestamp: time,
                app_id: app_id,
                interface_id: interface_id,
                biz_content: JSON.stringify(params),
            }
            if (header) {
                baseparams.header = JSON.stringify(header)
            }
            baseparams.sign = jpaasRequest.createSign(baseparams)
            try {
                const Response = await jpaasRequest.gateway(baseparams);
                return Response;
            } catch (error) {
                console.error('API请求失败:', error);
                throw error; // 继续向上抛出错误
            }

        } catch (error) {
            throw error
        }
    },

    /**
       * 基础请求方法
       * @param {string} url - 请求地址
       * @param {string} method - HTTP方法 (GET/POST/PUT/DELETE)
       * @param {Object} [params={}] - 请求参数
       * @param {Object} [headers={}] - 自定义请求头
       * @returns {Promise}
    */
    request: ({ url, method, params = {} }, headers = {}) => {
        return new Promise((resolve, reject) => {
            wx.request({
                url: url,
                method: method,
                data: params,
                header: {
                    'content-type': 'application/x-www-form-urlencoded',
                    ...headers // 合并自定义请求头
                },
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.data);
                    } else {
                        reject(new Error(`HTTP ${res.statusCode}: ${JSON.stringify(res.data)}`));
                    }
                },
                fail: (err) => {
                    reject(new Error(`网络错误: ${err.errMsg}`));
                }
            });
        });
    }
}
export default jpaasRequest